package cn.lyq.card.ui.income

import android.content.Context
import android.content.Intent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import cn.lyq.card.R
import cn.lyq.card.base.BaseActivity
import cn.lyq.card.data.model.IncomeWrapInfo
import cn.lyq.card.data.model.PageInfo
import cn.lyq.card.data.src.Status
import cn.lyq.card.global.BusTag
import cn.lyq.card.ui.achievement.DateSelectFg
import cn.lyq.card.utils.getVisibility
import cn.lyq.card.utils.setClick
import cn.lyq.card.utils.setSimpleData
import com.blankj.utilcode.util.BusUtils
import com.blankj.utilcode.util.ToastUtils
import com.flyco.tablayout.listener.OnTabSelectListener
import kotlinx.android.synthetic.main.act_income_detail.*
import kotlinx.android.synthetic.main.layout_tab_normal.*
import kotlinx.android.synthetic.main.layout_title.*
import java.text.SimpleDateFormat
import java.util.*


class IncomeDetailActivity : BaseActivity() {

    companion object {

        private const val KEY_TYPE = "TYPE"
        private const val KEY_DATE = "DATE"

        /** 0日、1月、2全部*/
        @JvmStatic
        fun start(context: Context, type: Int, date: Calendar) {
            val starter = Intent(context, IncomeDetailActivity::class.java)
                .putExtra(KEY_TYPE, type)
                .putExtra(KEY_DATE, date)
            context.startActivity(starter)
        }
    }

    private val daySdf = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)
    private val monthSdf = SimpleDateFormat("yyyy-MM", Locale.CHINA)
    private val date by lazy {
        val temp = intent.getSerializableExtra(KEY_DATE)
        if (temp is Calendar){
            temp
        }else{
            Calendar.getInstance()
        }
    }
    private val page = PageInfo()
    private val mModel by lazy {
        getVM(IncomeVM::class.java)
    }
    private val mAdapter by lazy {
        IncomeAdapter()
    }
    private val type by lazy {
        intent.getIntExtra(KEY_TYPE, 0)
    }

    override fun getLayoutId(): Int {
        return R.layout.act_income_detail
    }

    override fun initView() {
        super.initView()
        setMyTitle(R.string.str_income_detail)
        tvTitleSplit.visibility = View.GONE
        tvSelectDate.visibility = getVisibility(type == 2)
        tvDate.visibility = getVisibility(type == 2)
        tabLayout.setSimpleData(arrayOf("分润收益", "返现收益", "补贴收益"))

        if (type == 0) {
            tvDate.text = daySdf.format(date.time)
        } else {
            tvDate.text = monthSdf.format(date.time)
        }
        mAdapter.loadMoreModule.apply {
            checkDisableLoadMoreIfNotFullPage()
            preLoadNumber = 2
            setOnLoadMoreListener {
                getProfit(page.loadMore())
            }
        }
        rv.layoutManager = LinearLayoutManager(this)
        rv.adapter = mAdapter
        mAdapter.setEmptyView(R.layout.layout_empty)
    }

    override fun initListener() {
        super.initListener()
        tabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(p0: Int) {
                mModel.profitType = p0
                refreshLayout.isRefreshing = true
                getProfit(page.refresh())
            }

            override fun onTabReselect(p0: Int) {
            }

        })
        refreshLayout.setOnRefreshListener {
            getProfit(page.refresh())
        }
        bgDate.setClick {
            DateSelectFg.newInstance(type + 10, type == 0, date)
                .show(supportFragmentManager, "DateSelectFg")
        }
    }

    private fun getProfit(target: Int) {
        mModel.getProfit(type, tvDate.text.toString(), target)
            .observe(this, androidx.lifecycle.Observer {
                when (it?.status) {
                    Status.SUCCESS -> loadSuccess(it.requireData())
                    Status.ERROR -> {
                        page.fail()
                        refreshLayout.isRefreshing = false
                        mAdapter.loadMoreModule.loadMoreFail()
                        ToastUtils.showShort(it.message.getMsg())
                    }
                }
            })
    }


    private fun loadSuccess(it: IncomeWrapInfo) {
        tvAmount.text = "总金额：${it.price?:"0.00"}"
        tvNum.text = "共：${it.number}笔"
        if (page.isRefresh()) {
            mAdapter.setList(it.list)
        } else {
            mAdapter.addData(it.list)
        }
        page.success()
        if (it.list.size < mModel.pageSize) {
            mAdapter.loadMoreModule.loadMoreEnd()
        } else {
            mAdapter.loadMoreModule.loadMoreComplete()
        }
        refreshLayout.isRefreshing = false
    }

    override fun initObserver() {
        super.initObserver()
        refreshLayout.isRefreshing = true
        getProfit(page.refresh())
    }

    @BusUtils.Bus(tag = BusTag.DATE_SELECT, threadMode = BusUtils.ThreadMode.MAIN)
    fun selectDate(params: Triple<Int, String, Long>) {
        if (type + 10 == params.first) {
            tvDate.text = params.second
            date.timeInMillis = params.third
            refreshLayout.isRefreshing = true
            getProfit(page.refresh())
        }
    }
}